import axios, {AxiosError, type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type InternalAxiosRequestConfig} from "axios";
import {notification} from "ant-design-vue";
import ErrorAttributes from './ErrorAttributes';
// import storage from "store";
// import {ACCESS_TOKEN} from '../constants/index.js';
// import {useUserStore} from '../store/user';
import qs from "qs";

const axiosInstance = axios.create({
  baseURL: '192.168.1.1',
    timeout: 120000,
    withCredentials: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    }
})

axiosInstance.interceptors.request.use((config:InternalAxiosRequestConfig) => {
    // const token = storage.get(ACCESS_TOKEN);
    // if (token) {
    //     config.headers = {'Authorization': `Bearer ${token}`}
    // }
    return config;
}, handleError)

axiosInstance.interceptors.response.use(response => {
    if (response.request && response.request.responseType === 'blob') {
        try {
            handleFile(response);
        } catch (error) {
            console.log(error);
        }
    } else {
        return response.data;
    }
}, handleError)

function handleFile(response: AxiosResponse) {
    const link = document.createElement('a');
    const blob = response.data;
    // 获取heads中的filename文件名
    const _disp = response.headers['Content-Disposition'] || response.headers['content-disposition'];
    const temp = _disp?.split('attachment;fileName=')[1];
    const urlArr = response.request.responseURL.split('/');
    const fileName = decodeURIComponent(temp || urlArr[urlArr.length - 1]);
    link.style.display = 'none';
    const fileHref = link.href = URL.createObjectURL(blob);
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(fileHref);
}

notification.config({
    duration: 2
})

function handleError(error: AxiosError<ErrorAttributes>) {
    const status = error.response?.status;
    const data = error.response?.data;
    if (status === 401) { // 未登录
        // storage.remove(ACCESS_TOKEN)
        // const {logOut} = useUserStore()
        // logOut()
    } else if (status === 403) { // 无权限

    } else {
        notification.error({
            message: `错误:${data?.error}`,
            description: `原因:${data?.message}`
        })
        return Promise.reject(data);
    }
}

function axiosConfig<R>(config?: AxiosRequestConfig<R>, ...params: any): AxiosRequestConfig<R> {
    config ??= {};
    config.paramsSerializer = (params) => qs.stringify(params, {indices: false});
    if (params) {
        config.params = {};
        for (const param of params) {
            param && Object.assign(config.params, param);
        }
    }
    return config;
}

export interface AxiosRequestConfigEx<R> extends AxiosRequestConfig<R> {

}

class AxiosWrapper {
    public readonly axios: AxiosInstance;

    constructor(axios: AxiosInstance) {
        this.axios = axios;
    }

    get<R = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R> {
        return this.axios.get(url, config);
    }

    delete<R = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R> {
        return this.axios.delete(url, config);
    }

    post<R = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R> {
        return this.axios.post(url, data, config);
    }

    put<R = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R> {
        return this.axios.put(url, data, config);
    }
}

const axiosWrapper = new AxiosWrapper(axiosInstance);

export {axiosConfig};
export default axiosWrapper;


